<?php

namespace backend\services\goods;

use backend\extensions\ApiBaseService;
use backend\models\goods\goods\GoodsStock;
use backend\models\goods\goods\GoodsStockLog;

/**
 * Desc 商品库存服务类
 * @author WMX
 */
class GoodsStockService extends ApiBaseService
{

    /**
     * 列表
     * @param array $params 参数 
     * **/
    public static function getList($params)
    {
        // 检索条件
        $condition = ['AND'];
        if ($params['barcode']) {
            $condition[] = ['like', 'gt.barcode', $params['barcode']];
        }
        if ($params['name']) {
            $condition[] = ['like', 'gi.name', $params['name']];
        }
        $list = GoodsStock::getUnionAll($condition, $params['page'], $params['page_size']);

        return $list;
    }



    /**
     * 列表
     * @param array $params 参数 
     * **/
    public static function getLog($params)
    {
        // 检索条件
        $condition = ['AND'];
        if ($params['barcode']) {
            $condition[] = ['like', 'gtl.barcode', $params['barcode']];
        }
        if ($params['name']) {
            $condition[] = ['like', 'gi.name', $params['name']];
        }
        $list = GoodsStockLog::getUnionAll($condition, $params['page'], $params['page_size']);

        return $list;
    }




    public static function stockAdd($params)
    {
        $time = date('Y-m-d H:i:s');
        $stock_item = GoodsStock::getDataOne(['and', ['=', 'gid', $params['id']]]);
        if (empty($stock_item)) {
            $gt_id = GoodsStock::create([
                'gid' => $params['id'],
                'barcode' => $params['barcode'],
                'nums' => $params['nums']
            ]);
            // 库存日志变动
            GoodsStockLog::create([
                'gid' => $params['id'],
                'barcode' => $params['barcode'],
                'type' => 2,
                'nums' => $params['nums'],
                'create_time' => $time,
                'last' => 0,
                'curr' => $params['nums']
            ]);
        } else {
            $gt_id = $stock_item['id'];
            GoodsStock::updateData([
                'nums' => $stock_item['nums'] + $params['nums']
            ], ['id' => $gt_id]);
            // 库存日志变动
            GoodsStockLog::create([
                'gid' => $params['id'],
                'barcode' => $params['barcode'],
                'type' => 2,
                'nums' => $params['nums'],
                'create_time' => $time,
                'last' => $stock_item['nums'],
                'curr' => $stock_item['nums'] + $params['nums']
            ]);
        }
    }
}
